import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/home',
    name: 'Home',
    component: () => import('../views/Home.vue'),
    redirect: '/welcome',
    children: [
      {
        path: '/welcome',
        name: 'Welcome',
        component: () => import('../components/Welcome.vue')
      },
      {
        path: '/users',
        name: 'UserList',
        component: () => import('@/views/user/UserList.vue')
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 添加路由导航守卫
router.beforeEach((to, form, next) => {
  // 根据用户访问的路由进行判断,如果是登录页面正常访问,如果不是则需要判断用户是否登录
  if (to.path === '/login') return next()
  if (!window.sessionStorage.getItem('token')) return next('/login')
  return next()
})

export default router
